<template>
	<div class="container">
		<Breadcrumb :items="['menu.biz', 'menu.biz.tag']" />
		<a-card :title="$t('menu.biz.tag')">
			<a-space fill direction="vertical">
				<!-- 搜索表单 -->
				<a-form layout="inline" :model="searchForm" @submit="handleSearch">
					<a-form-item field="name" label="标签名称" :hide-label="true">
						<a-input v-model="searchForm.name" placeholder="请输入标签名称" allow-clear />
					</a-form-item>
					<a-form-item>
						<a-space>
							<a-button type="primary" html-type="submit" shape="round">
								<template #icon><icon-search /></template>
								搜索
							</a-button>
							<a-button shape="round" @click="resetSearch">
								<template #icon><icon-refresh /></template>
								重置
							</a-button>
						</a-space>
					</a-form-item>
				</a-form>

				<a-row :gutter="16">
					<a-col :span="12">
						<a-space fill>
							<a-button type="primary" @click="openModal()" shape="round">
								<template #icon><icon-plus /></template>
								添加标签
							</a-button>
						</a-space>
					</a-col>
				</a-row>

				<a-table :data="renderData" :loading="loading" :bordered="{ cell: true }" :pagination="pagination"
					@page-change="onPageChange" @page-size-change="onPageSizeChange">
					<template #columns>
						<a-table-column title="ID" data-index="id" :width="80" />
						<a-table-column title="标签名称" data-index="name" :width="150" />
						<a-table-column title="标签描述" data-index="description" :ellipsis="true" :tooltip="true" />
						<a-table-column title="关联商家数" data-index="biz_count" :width="120">
							<template #cell="{ record }">
								<a-tag :color="record.biz_count > 0 ? 'blue' : 'gray'">
									{{ record.biz_count || 0 }}
								</a-tag>
							</template>
						</a-table-column>
						<a-table-column title="创建时间" data-index="created_at" :width="180">
							<template #cell="{ record }">
								{{ formatDate(record.created_at) }}
							</template>
						</a-table-column>
						<a-table-column title="更新时间" data-index="updated_at" :width="180">
							<template #cell="{ record }">
								{{ formatDate(record.updated_at) }}
							</template>
						</a-table-column>
						<a-table-column title="操作" data-index="action" :width="150" fixed="right">
							<template #cell="{ record }">
								<a-space>
									<a-link @click="openModal(record)">编辑</a-link>
									<a-popconfirm position="left" content="确定要删除这个标签吗？" @ok="handleDelete(record.id)">
										<a-link>
											删除
										</a-link>
									</a-popconfirm>
								</a-space>
							</template>
						</a-table-column>
					</template>
				</a-table>
			</a-space>
		</a-card>

		<a-modal v-model:visible="modalVisible" width="600px" :draggable="true" :title="formData.id ? '编辑标签' : '添加标签'"
			@before-ok="handleSubmit" @cancel="closeModal">
			<a-form :model="formData" ref="formRef" layout="vertical">
				<a-form-item field="name" label="标签名称" :rules="[{ required: true, message: '请输入标签名称' }]">
					<a-input v-model="formData.name" placeholder="请输入标签名称" />
				</a-form-item>
				<a-form-item field="description" label="标签描述">
					<a-textarea v-model="formData.description" placeholder="请输入标签描述" :rows="4" />
				</a-form-item>
			</a-form>
		</a-modal>
	</div>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted } from 'vue';
import { Message } from '@arco-design/web-vue';
import useLoading from '@/hooks/loading';
import { Pagination } from '@/types/global';
import { queryBizTagList, submitBizTagForm, delBizTag, BizTagRecord } from '@/api/bizTag';

const { loading, setLoading } = useLoading(true);
const modalVisible = ref(false);
const formRef = ref();

// 搜索表单数据
const searchForm = reactive({
	name: '',
});

const basePagination = {
	current: 1,
	pageSize: 10,
	total: 0,
};

const pagination = reactive({
	...basePagination,
});

const generateFormData = () => {
	return {
		id: 0,
		name: '',
		description: ''
	};
};

const formData = ref(generateFormData());

const renderData = ref<BizTagRecord[]>([]);

const fetchData = async () => {
	setLoading(true);
	try {
		const { data } = await queryBizTagList({
			current: pagination.current,
			pageSize: pagination.pageSize,
			name: searchForm.name || undefined,
		});
		renderData.value = data.list;
		pagination.total = data.total;
	} catch (err) {
		Message.error('获取标签列表失败');
	} finally {
		setLoading(false);
	}
};

const onPageChange = (current: number) => {
	pagination.current = current;
	fetchData();
};

const onPageSizeChange = (pageSize: number) => {
	pagination.pageSize = pageSize;
	pagination.current = 1;
	fetchData();
};

// 搜索处理
const handleSearch = () => {
	pagination.current = 1;
	fetchData();
};

const openModal = (record?: BizTagRecord) => {
	if (record) {
		formData.value = {
			id: record.id,
			name: record.name,
			description: record.description
		};
	} else {
		formData.value = generateFormData();
	}
	modalVisible.value = true;
};

const closeModal = () => {
	modalVisible.value = false;
	formData.value = generateFormData();
};

const handleSubmit = async (done: (closed: boolean) => void) => {
	setLoading(true);
	try {
		const res = await submitBizTagForm(formData.value);
		Message.success('操作成功');
		closeModal();
		fetchData();
		done(true);
	} catch (err) {
		Message.error('操作失败');
		done(false);
	}
};

const handleDelete = async (id: number) => {
	setLoading(true);
	try {
		await delBizTag(id);
		Message.success('删除成功');
		fetchData();
	} catch (err) {
		Message.error('删除失败');
	} finally {
		setLoading(false);
	}
};

const resetSearch = () => {
	searchForm.name = '';
	pagination.current = 1;
	fetchData();
};

// 格式化日期
const formatDate = (timestamp: number) => {
	if (!timestamp) return '';
	const date = new Date(timestamp * 1000);
	return date.toLocaleString('zh-CN');
};

onMounted(() => {
	fetchData();
});
</script>

<style scoped lang="less">
.container {
	padding: 0 20px 20px 20px;
}
</style>

<script lang="ts">
export default {
	name: 'BizTag',
};
</script>
